﻿using System.Net.WebSockets;
using System.Text;

namespace Polaris.Common.Socket
{
    /// <summary>
    /// 业务逻辑处理
    /// </summary>
    public class BusMessageHandler : WebSocketHandler
    {
        public BusMessageHandler(WebSocketConnectionManager webSocketConnectionManager) : base(webSocketConnectionManager)
        {
        }

        /// <summary>
        /// socket连接
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public override async Task OnConnected(WebSocket socket)
        {
            await base.OnConnected(socket);
            var socketId = WebSocketConnectionManager.GetId(socket);
            await SendMessageToAllAsync($"{socketId}已加入");
        }

        /// <summary>
        /// socket断开
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public override async Task OnDisconnected(WebSocket socket)
        {
            await base.OnDisconnected(socket);
            var socketId = WebSocketConnectionManager.GetId(socket);
            await SendMessageToAllAsync($"{socketId}离开了");
        }

        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="result"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public override async Task ReceiveAsync(WebSocket socket, WebSocketReceiveResult result,string message)
        {
            var socketId = WebSocketConnectionManager.GetId(socket);
            var m = $"{socketId} 发送了消息：{message}";
            await SendMessageToAllAsync(m);
        }

        /// <summary>
        /// 根据socket获取id
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public async Task<string> GetIdBySocket(WebSocket socket)
        {
            return await Task.FromResult(WebSocketConnectionManager.GetId(socket));
        }

    }

}
